package hasthi.actuators.actions;

import hasthi.actuators.ActionContext;
import hasthi.common.HasthiException;
import hasthi.common.HasthiException.FaultCode;
import hasthi.metamodel.resource.ManagedResource;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommandGenerator {
    private static Pattern p1 = Pattern.compile(Pattern.quote("${Old.") + "(.*?)\\}");
    public static String insertVariables(ActionContext actionContext, ManagedResource oldResource,String cmd,String[][] mappings ) throws HasthiException {
        Matcher matcher = p1.matcher(cmd);
        while (matcher.find()) {
            String propertyName = matcher.group(1);
            String value = null;
            if (oldResource != null) {
                value = oldResource.getProperty(propertyName);
            } else if (mappings != null){
                for(String[] mapingVal:mappings ){
                    if(propertyName.equals(mapingVal[0])){
                        value = mapingVal[1];
                        break;
                    }
                }
            }
            if (value != null) {
                cmd = cmd.replace("${Old." + propertyName + "}", value);
            } else {
                throw new HasthiException("Command defined parameter " + propertyName
                        + " but the value not found in resource " + oldResource,
                        FaultCode.ConfigError);
            }
        }
        return cmd;
    }
}
